package com.blockmeta.bbs.businesslibrary.widget.chartview.Layer;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.RectF;


import com.blockmeta.bbs.baselibrary.utils.DimentionsUtil;
import com.blockmeta.bbs.baselibrary.utils.FormatUtil;
import com.blockmeta.bbs.businesslibrary.R;
import com.blockmeta.bbs.businesslibrary.websocket.Symbol;
import com.blockmeta.bbs.businesslibrary.widget.chartview.Axis.Coordinate;
import com.blockmeta.bbs.businesslibrary.widget.chartview.CandleData;
import com.blockmeta.bbs.businesslibrary.widget.chartview.CoinChart;
import com.blockmeta.bbs.businesslibrary.widget.tictactec.ta.lib.Core;
import com.blockmeta.bbs.businesslibrary.widget.tictactec.ta.lib.MAType;
import com.blockmeta.bbs.businesslibrary.widget.tictactec.ta.lib.MInteger;
import com.blockmeta.bbs.businesslibrary.widget.tictactec.ta.lib.RetCode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * kbar和boll的合并
 */
class KBarBollMoveLayer extends KBarMoveLayer
{
	private int beginIdx1;//用于存储第一个指标第一个值的位置
	private int mPeriod = 20;
	private int mDev = 2;

	private String m_mid = "", m_up = "", m_down = "";
	private String m_lastMid = "", m_lastUp = "", m_lastDown = "";
	private int m_color1 = 0xFFFFB100, m_color2 = 0xFFF05D47, m_color3 = 0xFF5897FF;
	private float mTxtXLocation;
	private int mNeedDrawIndex;
	private float txtSize;

	public KBarBollMoveLayer()
	{
		super();
	}


	@Override
	public boolean onCalculateData()
	{
		boolean m_bool_on = true;//FDTStorage.getInstance().getInteger(SaveKey.CHART_INDICATOR_BOLL + "on", SaveKey.CHART_INDICATOR_PARAM, 1) == 1 ? true : false;
		if (!m_bool_on)
		{
			tMAList = null;
			m_callback.setAdditionData(tMAList);//用于合并均线数据和k线数据的上下限
			return true;
		}

		ArrayList<String> params = new ArrayList<>(Arrays.asList("20", "2"));//FDTStorage.getInstance().getArray(SaveKey.CHART_INDICATOR_BOLL + "param", SaveKey.CHART_INDICATOR_PARAM);
		if (params != null)
		{
			mPeriod = FormatUtil.parseInt(params.get(0));
			mDev = FormatUtil.parseInt(params.get(1));
		}

		beginIdx1 = Integer.MAX_VALUE;

		List<CandleData> tDataList = m_callback.getCandleDataList();
		int tListSize = tDataList.size();
		tMAList = new ArrayList<CandleData>();
		double[] closes = new double[tListSize];

		for (int ii = 0; ii < tListSize; ii++)
		{
			closes[ii] = tDataList.get(ii).getDbClose();
		}
		//准备计算数组
		Core taLib = CoinChart.getTaLib();
		double[] mids = new double[tListSize];
		double[] ups = new double[tListSize];
		double[] downs = new double[tListSize];


		beginIdx1 = doBollCalculate(closes, taLib, mPeriod, mDev, mids, ups, downs);

		//得到结果数组,结果为有值的部分开始如0.006747350439404443 0.010591595301185919 0.0027601354459569905 -0.03422737187350222 -0.09373321549064784 -0.12136830634374718 -0.12757081986248053 -0.1250403123559245 -0.11954476938285197 -0.04594994628476812 0.009701854832457002 0.06010755762170561 0.09747712313834 0.13895129756983238 0.171272192598785 0.18158545677729165 0.15978420503275714 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
		//outBegIdx为是第几个开始的，outNbElement为有效的数字个数 ，如73个元素，那么outBegIdx为33，outNbElement为40 26-1+9-1=33
		CandleData candle = null;
		if (tListSize > 0)
		{
			int i1 = 0;
			for (int i = 0; i < tListSize; i++)//修改数据源
			{
				candle = new CandleData();

				double max = Double.MIN_VALUE;
				double min = Double.MAX_VALUE;
				if (i >= beginIdx1)
				{
					double mid = mids[i1];
					candle.setDbOpen(mid);

					double down = downs[i1];
					candle.setDbClose(down);
					if (down > max)
					{
						max = down;
					}
					if (down < min)
					{
						min = down;
					}

					double up = ups[i1];
					candle.setDbHigh(up);
					if (up > max)
					{
						max = up;
					}
					if (up < min)
					{
						min = up;
					}

					i1++;
				}
				else
				{
					candle.setDbOpen(0.0);
					candle.setDbClose(0.0);
					candle.setDbHigh(0.0);
				}


				//再把最大和最小算出来放到两个字段里面
				candle.setHighForward(max);
				candle.setLowForward(min);

				tMAList.add(candle);
			}


			m_callback.setAdditionData(tMAList);//用于合并均线数据和k线数据的上下限
		}
		return true;
	}


	public int doBollCalculate(double[] closes, Core taLib, int period, double pDev, double[] mid, double[] up, double[] down)
	{
		MInteger outBegIdx = new MInteger();
		MInteger outNbElement = new MInteger();

		RetCode retCode = taLib.bbands(0, closes.length - 1, closes, period, pDev, pDev, MAType.Sma, outBegIdx, outNbElement, up, mid, down);

		return outBegIdx.value;
	}

	@Override
	public void onDrawLayer(Canvas pCanvas, Paint pPaint, Point pPoint)
	{
		drawKbar(pCanvas, pPaint, pPoint);
		drawBoll(pCanvas, pPaint, pPoint);
	}

	private void drawBoll(Canvas pCanvas, Paint pPaint, Point pPoint)
	{
//		获取坐标系
		Coordinate tCoordinate = m_callback.getCoordinate();
		//转化处理数据
		List<CandleData> tDataList = tMAList;
		float scaleFactor = tCoordinate.getScaleFactor();


		if (tDataList != null && tDataList.size() > 0)
		{
			int tListSize = tDataList.size();

			float tXFirstPosition = tCoordinate.getXFirstPosition();
			float tXInterval = tCoordinate.getXInterval();
			float tYFirstposition = tCoordinate.getYFirstPosition();
			float tYMaxValue = tCoordinate.getMaxValue();
			float tYMinValue = tCoordinate.getMinValue();
			float tYValueDist = tYMaxValue - tYMinValue;
			float tYValueLength = tCoordinate.getValueHeight();

			float tCurrentYPosition = 0.f;
			float tTempYPosition = 0.f;
			float tCurrentXPosition = 0.f;
			float tTempXPosition = 0.f;

			float tCurrentYPosition1 = 0.f;
			float tTempYPosition1 = 0.f;

			float tCurrentYPosition2 = 0.f;
			float tTempYPosition2 = 0.f;


			float tLineWidth = 2.f;
			pPaint.setAntiAlias(true);

			int m_bDigit = m_callback.getDigit();
			//价格小数位数

			Symbol symbol = m_callback.getCoordinate().tSymBol;

			boolean tStartDraw1 = false;

			int tDotColor = R.color.sys_even;
			int tCulOffset = 1;

			int dataStart = getDataStartIndex(); //tStartIndex + getStartIndex();

			int moveStart = getMoveStartIndex();
			int displayCount = m_callback.getDisplayCount();//获取当前要显示的个数
			int minCount = Math.min(moveStart + displayCount, tListSize);//不能超出数据集宽度

			if (m_callback.isDrawAllData())//如果需要绘制全部数据的
			{
				dataStart = 0;
				moveStart = 0;
				minCount = tListSize;
			}

			if (dataStart > tListSize)//如果数据量不足以算出一个值
			{
				return;
			}
			CandleData candle = null;
			for (int i = moveStart; i < minCount; i++)
			{
				pPaint.setStrokeWidth(tLineWidth);

				candle = tDataList.get(i);

				float midValue = (float) candle.getDbOpen();
				float downValue = (float) candle.getDbClose();
				float upValue = (float) candle.getDbHigh();

				tTempXPosition = tCurrentXPosition;
				tCurrentXPosition = tXFirstPosition + tXInterval * (i - moveStart);
				if (midValue != 0.0)
				{

					tTempYPosition = tCurrentYPosition;
					tCurrentYPosition = tYFirstposition - ((midValue - tYMinValue) * tYValueLength / tYValueDist);

					tTempYPosition1 = tCurrentYPosition1;
					tCurrentYPosition1 = tYFirstposition - ((upValue - tYMinValue) * tYValueLength / tYValueDist);

					tTempYPosition2 = tCurrentYPosition2;
					tCurrentYPosition2 = tYFirstposition - ((downValue - tYMinValue) * tYValueLength / tYValueDist);

					if (tStartDraw1)
					{
						if (scaleFactor > 0.25)
						{
							RectF tRectF = tCoordinate.getLayerRectF();
							if (i > beginIdx1)
							{
								pPaint.setColor(m_color1);
								drawLine(pCanvas, pPaint, tCurrentYPosition, tTempYPosition, tCurrentXPosition, tTempXPosition, tRectF);

								pPaint.setColor(m_color2);
								drawLine(pCanvas, pPaint, tCurrentYPosition1, tTempYPosition1, tCurrentXPosition, tTempXPosition, tRectF);

								pPaint.setColor(m_color3);
								drawLine(pCanvas, pPaint, tCurrentYPosition2, tTempYPosition2, tCurrentXPosition, tTempXPosition, tRectF);
							}
						}
					}
					else
					{
						tStartDraw1 = true;
					}
				}

				if (((tCurrentXPosition - tXInterval / 2) <= pPoint.x && pPoint.x < (tCurrentXPosition + tXInterval / 2)) || ((i == minCount - 1) && pPoint.x > tCurrentXPosition + tXInterval / 2) || (i == moveStart && pPoint.x < tCurrentXPosition - tXInterval / 2))
				{
					m_mid = FormatUtil.getFormatString(midValue, m_bDigit);
					m_up = FormatUtil.getFormatString(upValue, m_bDigit);
					m_down = FormatUtil.getFormatString(downValue, m_bDigit);
				}


//				if (tDataList.get(i).m_bDrawDot)
//				{
//					pPaint.setColor(tDotColor);
//					pCanvas.drawCircle(tCurrentXPosition, tCurrentYPosition, tLineWidth * 2, pPaint);
//				}
			}

			candle = tDataList.get(minCount - 1);
			if (candle != null)
			{
				m_lastMid = FormatUtil.getFormatString(candle.getDbOpen(), m_bDigit);
				m_lastUp = FormatUtil.getFormatString(candle.getDbHigh(), m_bDigit);
				m_lastDown = FormatUtil.getFormatString(candle.getDbClose(), m_bDigit);
			}

		}
		else
		{
			resetIndicatorData();
		}
	}

	private void resetIndicatorData()
	{
		m_mid = "";
		m_up = "";
		m_down = "";
		m_lastMid = "";
		m_lastUp = "";
		m_lastDown = "";
	}

	private void drawLine(Canvas pCanvas, Paint pPaint, float tCurrentYPosition, float tTempYPosition, float tCurrentXPosition, float tTempXPosition, RectF tRectF)
	{
		pCanvas.drawLine(tTempXPosition, tTempYPosition, tCurrentXPosition, tCurrentYPosition, pPaint);
	}


	/**
	 * draw layer left－top text
	 * 获取指标值进行显示
	 *
	 * @param pCanvas
	 * @param pPaint
	 */
	@Override
	public void drawFloatIndicatorText(boolean longtouch, Canvas pCanvas, Paint pPaint)
	{

		if (!m_callback.needFloatIndicatorText())
		{
			return;
		}

		boolean m_boll_on = true;//FDTStorage.getInstance().getInteger(SaveKey.CHART_INDICATOR_BOLL + "on", SaveKey.CHART_INDICATOR_PARAM, 1) == 1 ? true : false;
		if (!m_boll_on)
		{
			return;
		}

		List<CandleData> tDataList = m_callback.getCandleDataList();
		if (tDataList == null || tDataList.size() == 0)
		{
			resetIndicatorData();
		}

		Coordinate tCoordinate = m_callback.getCoordinate();
		RectF tLayerRect = tCoordinate.getLayerRectF();
		RectF tChartRect = tCoordinate.getChartRectF();

		float tLeftPadding = DimentionsUtil.dp2px(0);
		float tButtomPadding = DimentionsUtil.dp2px(2);
		float tWordPadding = DimentionsUtil.dp2px(10);

		//根据需要添加相应的均线数据上去
		pPaint.reset();
		pPaint.setTextSize(DimentionsUtil.dp2px(10));
		pPaint.setAntiAlias(true);
		float textHeight = DimentionsUtil.dp2px(10);
		mTxtXLocation = tLayerRect.left + tLeftPadding;
		float space = 0.f;


		space = (tLayerRect.top - tChartRect.top - textHeight) / 2.f;
		space = space < 0 ? 0.f : space;

		txtSize = DimentionsUtil.dp2px(10);
		drawIndicator("MID", m_mid, m_lastMid, m_color1, longtouch, pCanvas, pPaint, tLayerRect, tWordPadding, space);
		drawIndicator("UP", m_up, m_lastUp, m_color2, longtouch, pCanvas, pPaint, tLayerRect, tWordPadding, space);
		drawIndicator("DOWN", m_down, m_lastDown, m_color3, longtouch, pCanvas, pPaint, tLayerRect, tWordPadding, space);

	}

	public void drawIndicator(String name, String cValue, String lastValue, int color, boolean longtouch, Canvas pCanvas, Paint pPaint, RectF tLayerRect, float tWordPadding, float tSpace)
	{
		String indicatorText;
		if (longtouch)
		{
			indicatorText = name + " " + cValue;
		}
		else
		{
			indicatorText = name + " " + lastValue;
		}
		float textWidth = pPaint.measureText(indicatorText);
		pPaint.setColor(color);
		float textY = tLayerRect.top + tSpace + txtSize;
		pCanvas.drawText(indicatorText, mTxtXLocation, textY, pPaint);
		mTxtXLocation += textWidth + tWordPadding;
	}


}
